package io.api.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Data
@Component
public class AliyunSendSmsService {

    @Value("${message.accessKeyId}")
    private String accessKeyId;

    @Value("${message.accessKeySecret}")
    private String accessKeySecret;

    @Value("${message.signName}")
    private String signName;

    @Value("${message.templateCode}")
    private String templateCode;

    @SneakyThrows
    public Client createClient(String accessKeyId, String accessKeySecret){
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }


    /**
     * 发送短信
     *
     * @param phoneNumber 手机号
     * @return 返回结果
     */
    @Async
    @SneakyThrows
    public SendSmsResponseBody sendMessage(String phoneNumber, String code) {
        Client client = createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam("{\"code\":\""+code+"\"}");
        RuntimeOptions runtime = new RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);

        SendSmsResponseBody body = response.getBody();
        log.info(body.getMessage());
//        return body;
        if(body.getCode().equals("OK")){
            return body;
        }else {
            throw new RuntimeException(body.getMessage());
        }
    }
}